package com.ruoyi.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.project.domain.entity.*;
import com.ruoyi.project.domain.query.ProjectFileQuery;
import com.ruoyi.project.domain.query.ProjectPayQuery;
import com.ruoyi.project.mapper.ProjectAttachmentMapper;
import com.ruoyi.project.mapper.ProjectPayMapper;
import com.ruoyi.project.service.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;


@Service
public class ProjectPayServiceImpl extends ServiceImpl<ProjectPayMapper, ProjectPay> implements IProjectPayService {

    @Resource
    private ProjectPayMapper projectPayMapper;

    @Resource
    private IPhaseDictionaryService dictionaryService;

    @Resource
    private IProjectService projectService;

    @Resource
    private IProjectPromissoryService promissoryService;



    //分页
    @Override
    public TableDataInfo getPage(ProjectPayQuery query) {
        Page<Object> page = PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<ProjectPay> list = projectPayMapper.getList(query);
        Project project = projectService.getById(query.getProjectNo());
        for (ProjectPay projectPay : list) {
            projectPay.setTotalAmount(project.getContractAmount());
        }
        return new TableDataInfo(list, page.getTotal());
    }

    //新增
    @Override
    public Boolean addInfo(ProjectPay project) {
        project.setOperator(SecurityUtils.getLoginUser().getUser().getNickName());
        Long phaseId = project.getPhaseId();
        if (phaseId == null) {
            throw new RuntimeException("后端接口异常");
        }
        PhaseDictionary byId = dictionaryService.getById(project.getPhaseId());
        project.setPhaseName(byId.getPhaseName());
        return this.save(project);
    }

    @Override
    public Boolean updateInfo(ProjectPay project) {
        project.setOperator(SecurityUtils.getLoginUser().getUser().getNickName());
        return this.updateById(project);
    }

    @Override
    public Boolean updateIds(ProjectPay project) {
        ProjectPay pay = projectPayMapper.selectById(project.getId());
        if (project.getSaleIds() != null && project.getSaleIds().size() > 0) {
            pay.setSaleIds(project.getSaleIds());
            return this.updateById(pay);
        }

        return true;
    }

    @Override
    public Boolean deleteInfo(String id) {
        return this.removeById(id);
    }

    @Override
    public ProjectPay getInfoById(String id) {
        return this.getById(id);
    }

    @Override
    public List<ProjectPay> getList(ProjectPayQuery query) {
        LambdaQueryWrapper<ProjectPay> wrapper = new QueryWrapper<ProjectPay>().lambda()
                .eq(query.getProjectNo() != null, ProjectPay::getProjectNo, query.getProjectNo())
                .eq(query.getPhaseId() != null, ProjectPay::getPhaseId, query.getPhaseId());
        List<ProjectPay> list = this.list(wrapper);
        Project project = projectService.getById(query.getProjectNo());
        String housekeeperProject = project.getHousekeeperProject();
        BigDecimal contractAmount = project.getSettlementAmount() != null ? project.getSettlementAmount() : project.getContractAmount() ;


        for (ProjectPay projectPay : list) {
            projectPay.setTotalAmount(project.getContractAmount());
            //如果有结算金额
            if (project.getContractAmount() != null) {
                projectPay.setSettlementAmount(project.getSettlementAmount());
            }

            //重新计算下收款比例
// 判断合同金额是否为空或零，防止除以零异常
            if (contractAmount == null || contractAmount.compareTo(BigDecimal.ZERO) <= 0) {
                // 合同金额无效时的默认处理，比如返回 0%
//                    projectPay.setPercentage();
            } else {
                // 计算百分比： (feeTotal / contractAmount) * 100
                double percentDouble = projectPay.getReceivedAmount().divide(contractAmount, 4, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal("100"))
                        .doubleValue();
                projectPay.setReceivedPercentage(percentDouble);
            }

        }

        //如果有期票 加上期票的 承兑的
        if (StringUtils.isNotEmpty(housekeeperProject)) {
            LambdaQueryWrapper<ProjectPromissory> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProjectPromissory::getHousekeeperProject, housekeeperProject);
            queryWrapper.in(ProjectPromissory::getNoteType, Arrays.asList("1","3","5"));//期票和承兑 保函
            List<ProjectPromissory> promissoryList = promissoryService.list(queryWrapper);
            for (ProjectPromissory projectPromissory : promissoryList) {
                ProjectPay pay = new ProjectPay();
                //期票金额
                pay.setPromissoryNote(projectPromissory.getMoney());
                //出票日期
                pay.setPayDate(projectPromissory.getOutDate());
                //付款单位
                pay.setCompany(projectPromissory.getPayer());
                //合同金额
                pay.setTotalAmount(project.getContractAmount());
                //备注
                pay.setRemark(projectPromissory.getRemark());
                //到期日期
                pay.setPromissoryEndDate(projectPromissory.getEndDate());

                //如果有结算金额
                    pay.setSettlementAmount(project.getSettlementAmount() != null ? project.getSettlementAmount() : project.getContractAmount());

                    // 计算百分比： (feeTotal / contractAmount) * 100
                    double percentDouble = pay.getPromissoryNote().divide(contractAmount, 4, RoundingMode.HALF_UP)
                            .multiply(new BigDecimal("100"))
                            .doubleValue();
                    pay.setReceivedPercentage(percentDouble);
                list.add(pay);
            }
        }

        return list;
    }

    @Override
    public void deleteByProjectNo(String projectNo) {
        projectPayMapper.deleteAllByProjectNo(projectNo);
    }

}
